// 处理设置面板的展开/折叠
export function setupSettings(toggleSettings, settingsPanel) {
  toggleSettings.addEventListener('click', () => {
    settingsPanel.classList.toggle('hidden')
    toggleSettings.textContent = settingsPanel.classList.contains('hidden')
      ? '设置'
      : '隐藏设置'
  })
}

// 处理API URL格式
export function formatApiUrl(url) {
  if (!url) return ''
  url = url.trim()
  if (!url.endsWith('/v1/chat/completions')) {
    url = url.replace(/\/v1\/?$/, '')
    url = url.replace(/\/?$/, '/v1/chat/completions')
  }
  return url
}

// 加载保存的设置
export function loadSettings(apiUrl, apiKey, debug) {
  chrome.storage.local.get(['apiUrl', 'apiKey'], (result) => {
    debug('加载原始设置:', result)
    const formattedUrl = formatApiUrl(result.apiUrl)
    apiUrl.value = formattedUrl || ''
    apiKey.value = result.apiKey || ''

    if (formattedUrl !== result.apiUrl) {
      chrome.storage.local.set({ apiUrl: formattedUrl }, () => {
        debug('已自动更新API URL格式')
      })
    }
    debug('格式化后的设置:', { apiUrl: formattedUrl, apiKey: result.apiKey })
  })
}

// 保存设置
export function saveSettings(apiUrl, apiKey, saveSettings, debug) {
  saveSettings.addEventListener('click', () => {
    const settings = {
      apiUrl: formatApiUrl(apiUrl.value),
      apiKey: apiKey.value,
    }
    debug('正在保存设置:', settings)

    chrome.storage.local.set(settings, () => {
      if (chrome.runtime.lastError) {
        debug('保存设置时出错:', chrome.runtime.lastError)
        alert('保存失败: ' + chrome.runtime.lastError.message)
      } else {
        debug('设置保存成功')
        alert('设置已保存')
      }
    })

    setTimeout(() => {
      chrome.storage.local.get(['apiUrl', 'apiKey'], (result) => {
        debug('验证保存的设置:', result)
      })
    }, 1000)
  })
}
